package oocl.ita.eordering.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Repository;

import oocl.ita.eordering.dao.MerchantDao;

import oocl.ita.eordering.po.Merchant;

@Repository("md")
public class MerchantDaoImpl implements MerchantDao {
	@PersistenceContext(name = "un")
	private EntityManager em;

	@Override
	public int addMerchant(Merchant merchant) {
		// TODO Auto-generated method stub
		em.persist(merchant);
		return merchant.getmId();
	}

	@Override
	public int updateMerchant(Merchant merchant) {
		// TODO Auto-generated method stub
		Merchant dbMerchant = em.find(Merchant.class, merchant.getmId());
		dbMerchant.setmBrand(merchant.getmBrand());
		dbMerchant.setmLocation(merchant.getmLocation());
		dbMerchant.setmLogoPath(merchant.getmLogoPath());
		return merchant.getmId();
	}

	@Override
	public Merchant findMerchantByTel(String mTel) {
		// TODO Auto-generated method stub
		String jpql = "select m from Merchant m where m.mTel=:mTel";
		@SuppressWarnings("unchecked")
		List<Merchant> ls = em.createQuery(jpql).setParameter("mTel", mTel).getResultList();
		if (ls.isEmpty())
			return null;
		else
			return ls.get(0);
	}

	@Override
	public Merchant findMerchantById(Integer mId) {
		// TODO Auto-generated method stub
		String jpql = "select m from Merchant m where m.mId=:mId";
		@SuppressWarnings("unchecked")
		List<Merchant> ls = em.createQuery(jpql).setParameter("mId", mId).getResultList();
		if (ls.isEmpty())
			return null;
		else
			return ls.get(0);
	}

	@Override
	public int updatePassword(Merchant merchant) {
		// TODO Auto-generated method stub
		Merchant dbMerchant = em.find(Merchant.class, merchant.getmId());
		dbMerchant.setmPassword(merchant.getmPassword());
		return merchant.getmId();
	}

}
